package com.xintoucloud.pbs.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.xintoucloud.pbs.entity.DynamicNews;
import com.xintoucloud.pbs.entity.DynamicNewsTopic;
import com.xintoucloud.pbs.model.DynamicNewsShowVo;
import com.xintoucloud.pbs.service.NewsManagementService;
import com.xintoucloud.pbs.service.NewsTopicManagementService;

@Controller
@RequestMapping("/NewsManagement")
public class NewsManagementController {
	
	@Autowired
	private NewsManagementService nmService;
	@Autowired
	private NewsTopicManagementService ntmService;
	
	
	@RequestMapping("/index")   //连接先进到控制器, 返回值在进入要显示数据的html页面NewsManagement2
	public String index(Model m) {
		List<DynamicNewsTopic> topics=ntmService.list();
		m.addAttribute("topics", topics);
		return "NewsManagement";
	}

	@RequestMapping("/other")   //连接先进到控制器, 返回值在进入要显示数据的html页面NewsManagement2
	public String other() {
		return "NewsView";
	}
	
	//展示所有新闻
	@RequestMapping("/list")  //NewsTopicManagement2页面读取其中的数据,当读到URL:list时, 进入到该方法,
	@ResponseBody			//把数据封装到map中,返回的map会被自动解析	
	public Map<String ,Object> list() {
		Map<String,Object> map = new HashMap<String,Object>();
		List<DynamicNewsShowVo> list = nmService.list();
		//List<DynamicNewsTopic> topics = ntmService.list();   //所有新闻栏目集合
		//list.get(1).setTopics(topics);    //把新闻栏目集合 放到第一个vo中
		map.put("code", 0);   //1,code:解析接口状态
		map.put("data",list); //2,msg:解析提示文本
		return map;			  //3,count:解析数据长度
							  //4,data:解析数据列表
	}

	
	//返回一条新闻的详细信息
	@RequestMapping("/newsDetail")  
	public String detail2(int nid, Model m) {
		DynamicNewsShowVo dnew = nmService.getOne(nid);
		m.addAttribute("newsVo", dnew);
		return "NewsDetail";			  
	}

	//返回一条新闻的详细信息  json数据到浏览器
	@RequestMapping("/newsDetail2") 
	@ResponseBody
	public DynamicNewsShowVo detail(int nid, Model m) {
		DynamicNewsShowVo dnew = nmService.getOne(nid);
		System.out.println(dnew.getTitle());
		return dnew;			  
	}
	
	
	//用于新闻添加时 下拉框选择栏目
	//但因为只有一个界面,所以页面中的表格会一次性加载,不能ajax异步请求得到数据后让表单再加载一次(要分清几个页面,搞清请求)
//	@RequestMapping("/topics")  
//	@ResponseBody			
//	public List<DynamicNewsTopic> getTopics(HttpSession session) {
//		List<DynamicNewsTopic> topics=ntmService.list();
//		session.setAttribute("topics", topics);
//		return topics;			 
//	}

	//删除一条新闻
	@RequestMapping("/delete")
	@ResponseBody	
	public  Map<String ,Object> delete(int nid) {
		Map<String,Object> map = new HashMap<String,Object>();
		boolean result = nmService.delete(nid);
		if(result) {
			map.put("msg", "恭喜您,删除成功!");
		}else {
			map.put("msg", "很遗憾,删除失败!");
		}
		return map;
	}

	//添加新闻
	@RequestMapping("/add")
	public String TopAdd(HttpServletRequest request) {
		DynamicNews dm = new DynamicNews();
		String title = request.getParameter("title");
		String source = request.getParameter("source");
		String time = request.getParameter("createtime");
		try {
			Date createtime = new SimpleDateFormat("yyyy-MM-dd").parse(time);
			dm.setCreatetime(createtime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		int ntid = Integer.parseInt(request.getParameter("ntid"));
		String content = request.getParameter("content");
		
		DynamicNewsTopic d = ntmService.getOne(ntid);
		
		dm.setTitle(title);
		dm.setSource(source);
		dm.setContent(content);
		dm.setDnt(d);
		
		boolean result = nmService.add(dm);
		return "redirect:index";  //重定向到界面
	}
	
	@RequestMapping("/update")
	public String update(DynamicNewsShowVo dnVo) {
		DynamicNews d = new DynamicNews();
		d.setNid(dnVo.getNid());
		d.setTitle(dnVo.getTitle());
		d.setSource(dnVo.getSource());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			d.setCreatetime(sdf.parse(dnVo.getCreatetime()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		d.setContent(dnVo.getContent());
		DynamicNewsTopic dt = ntmService.getOne(dnVo.getNtid());
		d.setDnt(dt);
		nmService.update(d);
		return "redirect:index";
	}
	
	//文件(图片)上传
	@ResponseBody 
    @RequestMapping("/uploadFile")
    public Map<String,Object> uploadFile(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String res = sdf.format(new Date());
        //服务器上使用  
        String rootPath = request.getServletContext().getRealPath("editImages");
        //本地使用
        //String rootPath ="/Users/lidong/Documents/uploads/";
        //原始名称
        String originalFilename = file.getOriginalFilename();
        //新的文件名称
        String newFileName = res+originalFilename.substring(originalFilename.lastIndexOf("."));
        //创建年月文件夹
//        Calendar date = Calendar.getInstance();
//        File dateDirs = new File(date.get(Calendar.YEAR)
//                + File.separator + (date.get(Calendar.MONTH)+1)); 
        //新文件
//        File newFile = new File(rootPath+File.separator+dateDirs+File.separator+newFileName);
        //File newFile = new File(rootPath+File.separator+newFileName);
        File newFile = new File("~/"+File.separator+newFileName);
        //判断目标文件所在的目录是否存在
//        if(!newFile.getParentFile().exists()) {
//            //如果目标文件所在的目录不存在，则创建父目录
//            newFile.getParentFile().mkdirs();
//        }
        System.out.println(newFile);
        //将文件输入系统,并输出到指定路径
        IOUtils.copy(file.getInputStream(),new FileOutputStream(rootPath+"/"+newFileName));
        //将内存中的数据写入磁盘
       // file.transferTo(newFile);
        //完整的url
//        String fileUrl =  "http://localhost:8080/uploads/"+date.get(Calendar.YEAR)+ "/"+(date.get(Calendar.MONTH)+1)+ "/"+ newFileName;
       
        //String fileUrl =  "http://localhost:8080/editImages/"+ newFileName;
        String fileUrl =  "/editImages/"+ newFileName;
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> map2 = new HashMap<String,Object>();
        map.put("code",0);//0表示成功，1失败
        map.put("msg","上传成功");//提示消息
        map.put("data",map2);
        map2.put("src",fileUrl);//图片url
        map2.put("title",newFileName);//图片名称，这个会显示在输入框里
        //String result = new JSONObject(map).toString();
        return map;
    }
	
}
